package com.cgtong.android.activity;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.BuildConfig;
import com.cgtong.android.R;
import com.cgtong.android.base.BaseActivity;
import com.cgtong.android.db.UserAccount;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.SplashContract;
import com.cgtong.android.mvp.presenter.SplashPresenter;
import com.cgtong.android.util.CommonUtils;
import com.umeng.analytics.MobclickAgent;
import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.exception.ApiException;
import com.cgtong.android.widget.SplashView;
import com.cgtong.android.bean.BannerBean;
import org.litepal.util.Const;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import com.zhouyou.http.callback.SimpleCallBack;
import com.blankj.utilcode.util.LogUtils;
import android.text.TextUtils;

public class SplashActivity extends BaseActivity implements SplashContract.View {

    private SplashPresenter mSplashPresenter;

    @BindView(R.id.loading_progress)
    ProgressBar mLoadingProgress;
    @BindView(R.id.jump_btn)
    Button mJumpBtn;
    //由于CountDownTimer有一定的延迟，所以这里设置3400
//    private CountDownTimer countDownTimer = new CountDownTimer(1000, 1000) {
//        @Override
//        public void onTick(long millisUntilFinished) {
//            mJumpBtn.setText("跳过(" + millisUntilFinished / 1000 + "s)");
//        }
//
//        @Override
//        public void onFinish() {
//            mJumpBtn.setText("跳过(" + 0 + "s)");
//            gotoMainActivity();
//        }
//    };

    private String mAdImageLink;
    private String mAdImageActionLink;
    private boolean isUserForbidden;

    @OnClick(R.id.jump_btn)
    protected void gotoMainActivity() {
//        countDownTimer.cancel();
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    public void initData() {
        initMobClickAgent();
        mJumpBtn.setVisibility(View.GONE);
        mLoadingProgress.setVisibility(View.VISIBLE);
        mSplashPresenter = new SplashPresenter(this);
        //检测版本更新
        CommonUtils.getversion(new CallBack<Integer>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onCompleted() { //完成、处于最新版本
                showMainPage();
            }

            @Override
            public void onError(ApiException e) {//请求版本更新失败
                showMainPage();
            }

            @Override
            public void onSuccess(Integer status) {//请求版本成功
                if (status == ConstantManager.VERSION_UPDATE_INGORE) { //忽略更新
                    showMainPage();
                } else if (status == ConstantManager.VERSION_UPDATE_NORMAL) { //正常更新
                    mLoadingProgress.setVisibility(View.GONE);
                    finish();
                } else if (status == ConstantManager.VERSION_UPDATE_UI) {
                    mLoadingProgress.setVisibility(View.GONE);
                }
            }
        });
    }

    private void showMainPage() {
        mSplashPresenter.getBannerList(new SimpleCallBack<List<BannerBean>>() {
            @Override
            public void onError(ApiException e) {
                checkUserToken();
            }

            @Override
            public void onSuccess(List<BannerBean> bannerBeen) {
                if(null!= bannerBeen && bannerBeen.size()>0){
                   BannerBean bannerObj =  bannerBeen.get(0);
                   mAdImageLink = bannerObj.getImageUrl();
                   mAdImageActionLink = bannerObj.getLink();
                }
                checkUserToken();
            }
        });
    }

    private void checkUserToken(){
        UserAccount userAccount = App.getInstance().getCurrentAccount();
        if (null != userAccount) {
            //mSplashPresenter.doLogin(userAccount.getPhone(), userAccount.getPassword());
            mSplashPresenter.getUserByToken(userAccount.getToken()); //->根据用户token获取用户信息
        } else {
            onLoginSuccess();
        }
    }

    @Override
    public void onLoginSuccess() {
//        mJumpBtn.setVisibility(View.VISIBLE);
//        countDownTimer.start();
        SPUtils.getInstance().put(ConstantManager.FIRST_TOKEN_VALIDATE, false);
        mLoadingProgress.setVisibility(View.GONE);
        //gotoMainActivity();
        if(TextUtils.isEmpty(mAdImageLink)){
            gotoMainActivity();
        }else{
            showSplashAdView();
        }
    }

    @Override
    public void onLoginError(int code) {
        SPUtils.getInstance().put(ConstantManager.FIRST_TOKEN_VALIDATE, false);
        mLoadingProgress.setVisibility(View.GONE);
        if (code == ConstantManager.ACCESS_TOKEN_EXPIRED) { //首次进入：Token失效
            UserAccount userAccount = App.getInstance().getCurrentAccount();
            if (null != userAccount) {  //更改用户状态
                userAccount.setToken("");
                userAccount.setLoginStatus(ConstantManager.LOGIN_OUT);
                App.getInstance().updateAccount(userAccount);
            }
            ToastUtils.showLong(getString(R.string.txt_relogin));
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra(LoginActivity.EXTRA_LOGINED_SHOW_PAGE, ConstantManager.MAIN_PAGE_INDEX);
            startActivity(intent);
            finish();
        } else if (code == ConstantManager.ACCESS_USER_FORBIDDEN) { //首次进入：用户禁用
            isUserForbidden = true;
            /*ToastUtils.showLong(getString(R.string.txt_relogin_forbidden));
            startActivity(new Intent(this, MainActivity.class));
            finish();*/
            if(TextUtils.isEmpty(mAdImageLink)){
                ToastUtils.showLong(getString(R.string.txt_relogin_forbidden));
                gotoMainActivity();
            }else{
                showSplashAdView();
            }
        } else {
            /*startActivity(new Intent(this, MainActivity.class));
            finish();*/
            if(TextUtils.isEmpty(mAdImageLink)){
                gotoMainActivity();
            }else{
                showSplashAdView();
            }
        }
    }

    private void showSplashAdView(){
        SplashView.showSplashView(this, 5, null, new SplashView.OnSplashViewActionListener() {
            @Override
            public void onSplashImageClick(String actionUrl) {
                if(!TextUtils.isEmpty(actionUrl) && !"null".equals(actionUrl)){
                    WebViewActivity.actionStart(SplashActivity.this,actionUrl,"ad");
                    finish();
                }
            }
            @Override
            public void onSplashViewDismiss(boolean initiativeDismiss) {
                LogUtils.i("SplashView", "dismissed, initiativeDismiss: " + initiativeDismiss);
                if(isUserForbidden){
                    ToastUtils.showLong(getString(R.string.txt_relogin_forbidden));
                }
                gotoMainActivity();
            }
            @Override
            public void onSplashImageNo(){
                if(isUserForbidden){
                    ToastUtils.showLong(getString(R.string.txt_relogin_forbidden));
                }
                gotoMainActivity();
            }
        });

        SplashView.updateSplashData(this,mAdImageLink,mAdImageActionLink);
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("启动页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("启动页");
        MobclickAgent.onPause(this);
    }

    /**
     * 初始友盟组件
     */
    private void initMobClickAgent() {
        MobclickAgent.setDebugMode(BuildConfig.DEBUG ? true : false);
        MobclickAgent.openActivityDurationTrack(false);
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
    }

    @Override
    public boolean setTranslucentStatusBar() {
        return true;
    }
}